package com.yequan.activemq.topic;

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

/**
 * @author : Administrator
 * @date : 2020/2/13
 */
public class ActiveMqTopicConsumer {

    public static void testTopicConsumer() {
        try {
            //1.创建一个connectionFactory连接工厂对象,指定IP和端口
            ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://192.168.0.1:61616");
            //2.使用connectionFactory对象创建连接对象
            Connection connection = connectionFactory.createConnection();
            //3.启动连接
            connection.start();
            //4.使用connection对象创建session对象
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            //5.使用session对象创建destination对象
            Topic topic = session.createTopic("topic:MQ:Psdb:common");
            //6.使用session对象创建consumer
            MessageConsumer consumer = session.createConsumer(topic);
            //7.接收消息
            consumer.setMessageListener(new MessageListener() {
                @Override
                public void onMessage(Message message) {
                    try {
                        TextMessage textMessage = (TextMessage) message;
                        String text = textMessage.getText();
                        System.out.println(text);
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            });
            System.out.println("消费者2启动");
            //等待接收消息
            System.in.read();
            //8.关闭资源
            consumer.close();
            session.close();
            connection.close();
        } catch (JMSException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        testTopicConsumer();
    }

}
